import {map, filter} from 'rxjs/operators';
import {Injectable} from "@angular/core";
import {Subject, Observable} from "rxjs";

interface BroadcastEvent {
    eventName: any;
    data?: any;
}

@Injectable()
export class BroadcastService {
    private _eventBus: Subject<BroadcastEvent>;

    constructor() {
        this._eventBus = new Subject<BroadcastEvent>();
    }

    broadcast(eventName: any, data?: any): void {
        this._eventBus.next({eventName, data});
    }

    on<T>(key: any): Observable<T> {
        return this._eventBus.asObservable().pipe(
            filter(event => event.eventName === key),
            map(event => <T>event.data),);
    }
}



